// 安装主进程模块解析修补，解决第三方包使用 entities 子路径导出在 Node exports 下不可用的问题
import { createRequire } from 'node:module'

const req = createRequire(import.meta.url)

try {
  // 通过 CJS 的 module 模块访问内部 _resolveFilename 钩子
  const ModuleCtor = req('module') as any
  const originalResolveFilename = ModuleCtor._resolveFilename

  ModuleCtor._resolveFilename = function patchedResolve(
    request: string,
    parent: any,
    isMain: boolean,
    options: any,
  ) {
    if (request === 'entities/decode') {
      try {
        return req.resolve('entities/lib/decode.js')
      }
      catch {}
    }
    if (request === 'entities/escape') {
      try {
        return req.resolve('entities/lib/escape.js')
      }
      catch {}
    }
    return originalResolveFilename.call(undefined as unknown as object, request, parent, isMain, options)
  }
}
catch {}
